from django.shortcuts import render, redirect, reverse, HttpResponse, Http404
from django.contrib.auth import logout, login, get_user_model
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt

from main.views import text_to_markdown


def logout_view(request):
    logout(request)
    return redirect(reverse('authentication:login'))


def register_view(request):
    username = password = password2 = ''
    errors = []
    if request.method == 'POST':
        data = request.POST
        username = data.get('username', '').strip()
        password = data.get('password', '')
        password2 = data.get('password2', '')
        if not (1 <= len(username) <= 15 and username.isidentifier()):
            errors.append('用户名不正确！（长度小于1位或大于15位，或者包含除下划线、数字、字母以外的字符或以数字开头）')
        if not (1 <= len(password) <= 100 and password == password2):
            errors.append('密码不正确！（长度小于1位或大于100位，或者两次密码不相同）')
        user_model = get_user_model()
        try:
            user_model.objects.get(username=username)
        except user_model.DoesNotExist:
            pass
        else:
            errors.append('用户已存在！')
        if not errors:
            user = user_model.objects.create_user(username=username, password=password)
            login(request, user)
            return redirect(reverse('main:index'))
    context = {
        'username': username,
        'password': password,
        'password2': password2,
        'errors': errors,
    }
    return render(request, 'authentication/register.html', context)


@login_required
@require_POST
@csrf_exempt
def change_image_view(request):
    image = request.FILES.get('image')
    if image is not None:
        request.user.image = image
        request.user.save()
    else:
        raise Http404
    return HttpResponse()


@login_required
def setting_view(request):
    old_password = password = password2 = ''
    done = False
    first = True
    errors = []
    if request.method == 'POST':
        first = False
        data = request.POST
        old_password = data.get('old-password', '')
        password = data.get('password', '')
        password2 = data.get('password2', '')
        if not request.user.check_password(old_password):
            errors.append('旧密码不正确！')
        if password or password2:
            if not (1 <= len(password) <= 100 and password == password2):
                errors.append('新密码不正确！（长度小于1位或大于100位，或者两次密码不相同）')
        if not errors:
            if password:
                request.user.set_password(password)
                done = True
            if done:
                request.user.save()
                old_password = password = password2 = ''
    context = {
        'old_password': old_password,
        'password': password,
        'password2': password2,
        'errors': errors,
        'done': done,
        'first': first,
    }
    return render(request, 'authentication/setting.html', context)


@login_required
@require_POST
def change_homepage_view(request):
    homepage = request.POST.get('content', '').strip()
    if request.user.identity is None or text_to_markdown(homepage) == '':
        raise Http404
    request.user.homepage = homepage
    request.user.save()
    return redirect(reverse('main:believer', args=(request.user.id, )))
